package com.zyc.provider.impl;


import com.zyc.enums.RpcErrorMessageEnum;
import com.zyc.exception.RpcException;
import com.zyc.provider.ServiceProvider;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 不用注册中心的简易容器
 * @author zyc
 * @create 2022--05--09 16:48
 */
@Slf4j
public class ServiceProviderImpl implements ServiceProvider {
    private final Map<String, Object> serviceMap;

    public ServiceProviderImpl() {
        serviceMap = new ConcurrentHashMap<>();
    }

    @Override
    public void addService(Object rpcService) {
        String rpcServiceName = rpcService.getClass().getInterfaces()[0].getCanonicalName();
        if (serviceMap.containsKey(rpcServiceName)) {
            return;
        } else {
            serviceMap.put(rpcServiceName, rpcService);
        }
        log.info("添加服务:{} 其接口为:{}", rpcServiceName, rpcService.getClass().getInterfaces());
    }

    @Override
    public Object getService(String rpcServiceName) throws RpcException {
        Object service = serviceMap.get(rpcServiceName);
        if (service == null) {
            throw new RpcException(RpcErrorMessageEnum.SERVICE_CAN_NOT_BE_FOUND);
        }
        return service;
    }

    @Override
    public void publishService(Object rpcService) {

    }

    @Override
    public void publishService(Object rpcService, int port) {

    }

}
